package com.ysy.logistics.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysy.common.resp.ResultData;
import com.ysy.logistics.entities.system.Dict;
import com.ysy.logistics.entities.system.dto.DictDto;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.system.DictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/19 9:52
 **/
@Slf4j
@RestController
@RequestMapping(value = "/sysDict",name = "字典")
@Tag(name = "字典管理",description = "dict表的CRUD")
@CrossOrigin
public class DictController {

    @Resource
    private DictService dictService;

    @GetMapping(value = "/list")
    @Operation(summary = "获取字典")
    public ResultData list(@RequestParam(value = "name",required = false) String name){
        if (StringUtils.isNotEmpty(name)) {
            List<DictDto> dicts = dictService.findByNameLike(name);
            return ResultData.success(dicts);
        }
        return ResultData.success(dictService.findByPid(0L));
    }

    @PostMapping(value = "/add")
    @Operation(summary = "添加字典")
    @OperateLog("添加字典")
    public ResultData add(@RequestBody DictDto dict){
        //判断
        if (StringUtils.isEmpty(dict.getName())) {
            return ResultData.fail("参数名称不能为空");
        }
        return dictService.addDict(dict);
    }

    @PostMapping(value = "/update")
    @Operation(summary = "修改字典")
    @OperateLog("修改字典")
    public ResultData update(@RequestBody DictDto dict){
        //判断
        if (StringUtils.isEmpty(dict.getName())|| dict.getId()==null) {
            return ResultData.fail("参数名称不能为空");
        }
        return dictService.update(dict);
    }

    @GetMapping(value = "/delete/{id}")
    @Operation(summary = "删除字典")
    @OperateLog("删除字典")
    public ResultData delete(@PathVariable("id") Long id){
        //查出
        Dict dict = dictService.getById(id);
        if(Objects.isNull(dict)){
            return ResultData.fail("字典不存在");
        }
        dictService.removeById(id);
        //删除子节点
        dictService.remove(new LambdaQueryWrapper<Dict>().eq(Dict::getPid,id));
        return ResultData.success();
    }

    @GetMapping(value = "/getDicts/{name}")
    @Operation(summary = "根据字典名称获取字典")
    public ResultData<List<DictDto>> getDicts(@PathVariable("name") String dictName) {
        List<DictDto> dicts = dictService.getDictsByPname(dictName);
        return  ResultData.success(dicts);
    }
}
